/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.cloud.all.security.config.annotation.web.configurers.oauth2.client;

import cn.cloud.all.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import cn.cloud.all.security.config.web.HttpSecurityBuilder;
import org.springframework.util.Assert;

public final class ImplicitGrantConfigurer<B extends HttpSecurityBuilder<B>> extends AbstractHttpConfigurer<ImplicitGrantConfigurer<B>, B> {

    private String authorizationRequestBaseUri;

    /**
     * Sets the base {@code URI} used for authorization requests.
     *
     * @param authorizationRequestBaseUri the base {@code URI} used for authorization requests
     * @return the {@link ImplicitGrantConfigurer} for further configuration
     */
    public ImplicitGrantConfigurer<B> authorizationRequestBaseUri(String authorizationRequestBaseUri) {
        Assert.hasText(authorizationRequestBaseUri, "authorizationRequestBaseUri cannot be empty");
        this.authorizationRequestBaseUri = authorizationRequestBaseUri;
        return this;
    }

    /**
     * Sets the repository of client registrations.
     *
     * @param clientRegistrationRepository the repository of client registrations
     * @return the {@link ImplicitGrantConfigurer} for further configuration
     */
    public ImplicitGrantConfigurer<B> clientRegistrationRepository(ClientRegistrationRepository clientRegistrationRepository) {
        Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
        this.getBuilder().setSharedObject(ClientRegistrationRepository.class, clientRegistrationRepository);
        return this;
    }

    @Override
    public void configure(B http) {
        OAuth2AuthorizationRequestRedirectFilter authorizationRequestFilter = new OAuth2AuthorizationRequestRedirectFilter(OAuth2ClientConfigurerUtils.getClientRegistrationRepository(this.getBuilder()), this.getAuthorizationRequestBaseUri());
        http.addFilter(this.postProcess(authorizationRequestFilter));
    }

    private String getAuthorizationRequestBaseUri() {
        return this.authorizationRequestBaseUri != null ?
                this.authorizationRequestBaseUri : OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI;
    }
}
